import React, { useState } from 'react'; // 导入React和useState
import { Table, Button, Modal, Form, Input, Space, message, Popconfirm, Card, Tag, Row, Col, Statistic } from 'antd'; // 导入Ant Design组件
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, DownloadOutlined, FileTextOutlined } from '@ant-design/icons'; // 导入图标

// 初始报表数据
const initialReports = [
  { id: 1, name: '销售报表', type: '月报', status: 'enabled', recordCount: 1200, remark: '每月自动生成' },
  { id: 2, name: '库存报表', type: '周报', status: 'disabled', recordCount: 300, remark: '' }
];

const ReportManagement = () => {
  // 报表列表
  const [reports, setReports] = useState(initialReports);
  // 控制模态框显示
  const [modalVisible, setModalVisible] = useState(false);
  // 当前编辑报表
  const [editing, setEditing] = useState(null);
  // 预览模态框显示
  const [previewVisible, setPreviewVisible] = useState(false);
  // 当前预览报表
  const [previewReport, setPreviewReport] = useState(null);
  // 表单实例
  const [form] = Form.useForm();

  // 统计面板数据
  const stats = {
    total: reports.length,
    enabled: reports.filter(r => r.status === 'enabled').length,
    disabled: reports.filter(r => r.status === 'disabled').length,
    totalRecords: reports.reduce((sum, r) => sum + r.recordCount, 0)
  };

  // 打开新增报表模态框
  const handleAdd = () => {
    setEditing(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 打开编辑报表模态框
  const handleEdit = (record) => {
    setEditing(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  // 删除报表
  const handleDelete = (id) => {
    setReports(reports.filter(item => item.id !== id));
    message.success('删除成功');
  };

  // 预览报表
  const handlePreview = (record) => {
    setPreviewReport(record);
    setPreviewVisible(true);
  };

  // 导出报表
  const handleExport = (record) => {
    message.success(`报表【${record.name}】导出成功（模拟）`);
  };

  // 提交表单
  const handleOk = () => {
    form.validateFields().then(values => {
      if (editing) {
        // 编辑报表
        setReports(reports.map(item => item.id === editing.id ? { ...item, ...values } : item));
        message.success('编辑成功');
      } else {
        // 新增报表
        const newItem = { id: Date.now(), ...values, status: 'enabled', recordCount: 0 };
        setReports([...reports, newItem]);
        message.success('新增成功');
      }
      setModalVisible(false);
      form.resetFields();
    });
  };

  // 报表表格列
  const columns = [
    { title: '名称', dataIndex: 'name', key: 'name' },
    { title: '类型', dataIndex: 'type', key: 'type' },
    { title: '状态', dataIndex: 'status', key: 'status', render: (text) => text === 'enabled' ? <Tag color="green">启用</Tag> : <Tag color="red">禁用</Tag> },
    { title: '记录数', dataIndex: 'recordCount', key: 'recordCount' },
    { title: '备注', dataIndex: 'remark', key: 'remark' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button icon={<EyeOutlined />} size="small" onClick={() => handlePreview(record)}>预览</Button>
          <Button icon={<DownloadOutlined />} size="small" onClick={() => handleExport(record)}>导出</Button>
          <Button icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm title="确定删除该报表吗？" onConfirm={() => handleDelete(record.id)} okText="确定" cancelText="取消">
            <Button icon={<DeleteOutlined />} size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <Card title="报表管理" bordered={false}> {/* 外层卡片 */}
      {/* 统计面板 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}><Statistic title="报表总数" value={stats.total} prefix={<FileTextOutlined />} /></Col>
        <Col span={6}><Statistic title="启用报表" value={stats.enabled} valueStyle={{ color: '#3f8600' }} /></Col>
        <Col span={6}><Statistic title="禁用报表" value={stats.disabled} valueStyle={{ color: '#cf1322' }} /></Col>
        <Col span={6}><Statistic title="总记录数" value={stats.totalRecords} /></Col>
      </Row>
      <Button type="primary" icon={<PlusOutlined />} style={{ marginBottom: 16 }} onClick={handleAdd}>新增报表</Button>
      <Table columns={columns} dataSource={reports} rowKey="id" pagination={false} />
      <Modal
        title={editing ? '编辑报表' : '新增报表'}
        open={modalVisible}
        onOk={handleOk}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="名称" rules={[{ required: true, message: '请输入名称' }]}> 
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item name="type" label="类型" rules={[{ required: true, message: '请输入类型，如月报/周报' }]}> 
            <Input placeholder="请输入类型，如月报/周报" />
          </Form.Item>
          <Form.Item name="remark" label="备注"> 
            <Input placeholder="备注（可选）" />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="报表预览"
        open={previewVisible}
        onOk={() => setPreviewVisible(false)}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
      >
        {previewReport && (
          <div>
            <p><b>名称：</b>{previewReport.name}</p>
            <p><b>类型：</b>{previewReport.type}</p>
            <p><b>状态：</b>{previewReport.status === 'enabled' ? '启用' : '禁用'}</p>
            <p><b>记录数：</b>{previewReport.recordCount}</p>
            <p><b>备注：</b>{previewReport.remark}</p>
            <div style={{ marginTop: 16, color: '#888' }}><FileTextOutlined /> 这里是报表内容预览（模拟）</div>
          </div>
        )}
      </Modal>
    </Card>
  );
};

export default ReportManagement; // 导出报表管理组件 